package mysql

import (
	"crypto/md5"
	"encoding/hex"
	"web_app/models"
)

const secret = "zhouJun"

// InsertUser 插入一条用户信息
func InsertUser(user *models.User) (err error) {
	user.Password = encryptPassword(user.Password)
	sqlStr := "insert into user(user_id,username,password) values(?,?,?)"
	_, err = db.Exec(sqlStr, user.UserID, user.UserName, user.Password)
	return
}

// CheckUserExist 通过用户姓名检查用户是否存在
func CheckUserExist(UName string) (err error) {
	sqlStr := "select count(user_id) from user where username=?"
	var count int
	if err = db.Get(&count, sqlStr, UName); err != nil {
		return err
	}
	if count > 0 {
		return ErrUserExist
	}
	return
}

//根据用户名密码匹配用户
func GetUser(user *models.User) (err error) {
	sqlStr := "select user_id,username,password from user where username=?"
	oPassword := user.Password
	if err = db.Get(user, sqlStr, user.UserName); err != nil {
		return err
	}
	if encryptPassword(oPassword) != user.Password {
		return ErrInvalidPassword
	}
	return
}

//用户密码Md5加密
func encryptPassword(oPassword string) string {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum([]byte(oPassword)))
}
